package com.pincai;

import java.sql.*;
import java.util.*;
import java.util.Map.Entry;

public class Utils {
    private final String url = "jdbc:mysql://rm-bp1rqx1ig1rzp85v0o.mysql.rds.aliyuncs.com:3306/heiyu_test?characterEncoding=utf-8&useSSL=false";
    private final String userName = "heiyu_test";
    private final String password = "96a9519b";

   // private final String url = "jdbc:mysql://120.26.68.235:3306/miliao?characterEncoding=utf-8&useSSL=false";
    //private final String userName = "miliao";
    //private final String password = "Miliao2018!";
    private Connection conn;
    public Map<String, Object> map;
    private Map<String, List<String[]>> mapList;
    private Map<String,String> privateKeys;

    private String[] tables = {"t_user_activity_info","t_activity_info","t_user_invite","t_user_balance","t_user_balance_type","t_user_balance_seq"};

    public void connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getTables() throws SQLException {
        map = new HashMap<String, Object>();
        mapList = new HashMap<String, List<String[]>>();
        for (int i = 0; i < tables.length; i++) {
            map.put(autoUpCase(tables[i],true), tables[i]);
        }
    }

    public void dealTableColumn() {
        String sql = "select * from ";
        Statement sta;
        ResultSet rs;
        try {
            Iterator it = map.entrySet().iterator();
            Entry<String, Object> entry;
            while (it.hasNext()) {
                entry = (Entry<String, Object>) it.next();
                sta = conn.createStatement();
                /*rs = conn.getMetaData().getPrimaryKeys(null,null,entry.getValue().toString());
                if(privateKeys == null){
                    privateKeys = new HashMap<String,String>();
                }
                if (!rs.isAfterLast()) {
                    rs.next();
                    privateKeys.put(entry.getKey(),rs.getString("COLUMN_NAME"));

                }*/
                rs = sta.executeQuery(sql + " " + entry.getValue()+" limit 0,10");
                ResultSetMetaData columnData = rs.getMetaData();
                String[] labels = new String[columnData.getColumnCount()];
                String[] types = new String[columnData.getColumnCount()];
                String[] columns = new String[columnData.getColumnCount()];
                for (int i = 0; i < labels.length; i++) {
                    columns[i] = columnData.getColumnLabel(i + 1);
                    labels[i] = this.autoUpLowerCase(columnData.getColumnLabel(i + 1));
                    types[i] = switchType(columnData.getColumnTypeName(i + 1));
                }

                List<String[]> list = new ArrayList<String[]>();
                list.add(labels);
                list.add(types);
                list.add(columns);
                mapList.put(entry.getKey(), list);
                rs.close();
                sta.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            conn.close();
            conn = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn = null;
            }
        }
    }

    public static String autoUpCase(String name,boolean flag) {
        String[] names = name.split("_");
        StringBuilder sb = new StringBuilder();
        int i=0;
        if(flag)
            i=1;

        for(;i<names.length;i++){
            sb.append(names[i].substring(0,1).toUpperCase()).append(names[i].substring(1));
        }
        return sb.toString();
    }

    public String autoUpLowerCase(String name) {
        String[] names = name.split("_");
        if(names.length==1){
            return name;
        }
        StringBuilder sb = new StringBuilder(names[0]);
        for(int i=1;i<names.length;i++){
            sb.append(autoUpCase(names[i],false));
        }
        return sb.toString();
    }

    public String switchType(String source) {
        if (source.toLowerCase().equals("int") || source.toUpperCase().equals("TINYINT UNSIGNED")||source.toLowerCase().equals("int unsigned")
                ||source.toUpperCase().equals("TINYINT")||source.toUpperCase().equals("SMALLINT")) {
            return "Integer";
        }
        if( source.toUpperCase().equals("BIGINT UNSIGNED")){
            return "Long";
        }
        if (source.toLowerCase().equals("varchar")) {
            return "String";
        }

        if (source.toLowerCase().equals("char")) {
            return "String";
        }

        if (source.toUpperCase().equals("DOUBLE")||source.toUpperCase().equals("DECIMAL")) {
            return "BigDecimal";
        }
        if (source.toLowerCase().equals("text")) {
            return "String";
        }

        if (source.toLowerCase().equals("timestamp")) {
            return "Date";
        }

        if (source.toLowerCase().equals("date")) {
            return "Date";
        }
        if (source.toLowerCase().equals("datetime")) {
            return "Date";
        }

        if (source.toLowerCase().equals("bigint")) {
            return "Long";
        }

        if (source.toLowerCase().equals("float")) {
            return "float";
        }

        if (source.toLowerCase().equals("bit")) {
            return "byte";
        }
        return source;
    }

    public Map<String, List<String[]>> doAll() {
        connect();
        try {
            getTables();
            dealTableColumn();
            close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapList;
    }

}
